package com.cow.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cow.mapper.GoodMapper;
import com.cow.mapper.ShoppingCartMapper;
import com.cow.pojo.Good;
import com.cow.pojo.ShoppingCart;
import com.cow.pojo.ShoppingCartExample;
import com.cow.util.GoodUtilBean;

/**
 * @author 光环and鬼泣
 * @version 2018年6月1日 下午3:52:40
 */
@Service("shoppingCartService")
public class ShoppingCartServiceImpl implements com.cow.service.ShoppingCartService {

	@Autowired
	private ShoppingCartMapper shoppingCartMapper = null;
	@Autowired
	private GoodMapper goodMapper = null;

	@Override
	public int addGoodToShoppingCart(ShoppingCart shoppingCart) throws Exception {
		int result = 0;
		ShoppingCartExample example = new ShoppingCartExample();
		ShoppingCartExample.Criteria criteria = example.createCriteria();
		criteria.andGoodIdEqualTo(shoppingCart.getGoodId());
		criteria.andUserIdEqualTo(shoppingCart.getUserId());
		List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectByExample(example);
		if (shoppingCartList.size() > 0) {
			ShoppingCart shoppingCart1 = shoppingCartList.get(0);
			shoppingCart1.setGoodNumber(String.valueOf(
					Integer.parseInt(shoppingCart.getGoodNumber()) + Integer.parseInt(shoppingCart1.getGoodNumber())));
			result = shoppingCartMapper.updateByExample(shoppingCart1, example);
		} else {
			result = shoppingCartMapper.insert(shoppingCart);
		}
		return result;
	}

	@Override
	public int deleteGoodToShoppingCart(String goodId, String userId) throws Exception {
		ShoppingCartExample example = new ShoppingCartExample();
		ShoppingCartExample.Criteria criteria = example.createCriteria();
		criteria.andGoodIdEqualTo(goodId);
		criteria.andUserIdEqualTo(userId);
		int result = shoppingCartMapper.deleteByExample(example);
		return result;
	}

	@Override
	public List<GoodUtilBean> getShoppingCart(String userId) throws Exception {
		ShoppingCartExample example = new ShoppingCartExample();
		ShoppingCartExample.Criteria criteria = example.createCriteria();
		criteria.andUserIdEqualTo(userId);
		List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectByExample(example);
		List<GoodUtilBean> goodList = new ArrayList<GoodUtilBean>();
		for (ShoppingCart shoppingCart : shoppingCartList) {
			Good good = goodMapper.selectByPrimaryKey(shoppingCart.getGoodId());
			GoodUtilBean goodUtilBean = new GoodUtilBean(good);
			goodUtilBean.setGoodNumber(shoppingCart.getGoodNumber());
			goodList.add(goodUtilBean);
		}
		return goodList;
	}

}
